import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import {
  Button,
  Form,
  Input,
  InputNumber,
  Modal,
  Space,
  Utils,
} from "knowdesign";
import message from "@/components/Message";

// 引入代码编辑器

import "codemirror/lib/codemirror.css";
//代码高亮
import "codemirror/addon/edit/matchbrackets";
import "codemirror/addon/selection/active-line";
import "codemirror/addon/edit/closebrackets";
require("codemirror/mode/xml/xml");
require("codemirror/mode/javascript/javascript");
import api from "./api";

import { ConfigOperate, ConfigProps, sourceList } from "./config";
import "./index.less";
import SearchFilter from "./SearchFilter";
import HttpUtils from "@/utils/HttpUtils";
import TextArea from "knowdesign/lib/basic/input/TextArea";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";

// 新增/编辑配置抽屉
const AddAndEditDataSourceModal = forwardRef((_, ref) => {
  const [config, setConfig] = useState<ConfigProps>({});
  const [type, setType] = useState<ConfigOperate>(ConfigOperate.Add);
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [cloneVisible, setCloneVisible] = useState<boolean>(false);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const callback = useRef(() => {
    return;
  });
  const [showOk, setShowOk] = useState(false);
  const [dsType, setDsType] = useState("");
  // 校验 IP 地址的正则表达式
  const ipRegex =
    /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

  useEffect(() => {
    console.log("--------------");
  }, []);

  // 提交表单
  const onSubmit = () => {
    form.validateFields().then((formData) => {
      setConfirmLoading(true);
      formData.dsType = dsType;
      console.log(config);
      if (type === ConfigOperate.Edit) {
        formData.dsType = config.dsType;
        formData.url = config.url;
        formData.status = config.status;
      }

      //   formData.customParams = JSON.stringify(formData.customParams);

      const isAdd = type === ConfigOperate.Add;
      const submitApi = isAdd ? api.addSource : api.editSource;

      HttpUtils.request(submitApi, isAdd ? "PUT" : "POST", {
        data: Object.assign(formData, isAdd ? {} : { id: config.id }),
      }).then(
        (res) => {
          if (res?.code === 200) {
            onClose();
            setShowOk(false);
            setDsType("");
            console.log(res);
            // 执行回调，刷新列表数据
            callback.current();

            message.success(`成功${isAdd ? "新增" : "更新"}数据源`);
          } else {
            message.error(res?.message);
          }
        },
        () => setConfirmLoading(false)
      );
    });
  };

  const cloneDs = (config: ConfigProps = {}) => {
    setCloneVisible(true);
    form.setFieldsValue({ dsName: config.dsName });
    setConfig(config);
  };

  // 展开抽屉
  const onOpen = (
    status: boolean,
    type: ConfigOperate,
    cbk: () => void,
    groupOptions,
    config: ConfigProps = {}
  ) => {
    if (config.value) {
      try {
        // 如果内容可以格式化为 JSON，进行处理
        config.value = JSON.stringify(JSON.parse(config.value), null, 2);
      } catch (_) {
        //
      }
    }
    console.log(config);
    form.setFieldsValue({ ...config, status: config.status === 1 });
    setConfig(config);
    setType(type);
    setDsType(config.dsType);
    setVisible(status);
    callback.current = cbk;
  };

  // 关闭抽屉
  const onClose = () => {
    setVisible(false);
    setConfirmLoading(false);
    setConfig({});
    form.resetFields();
    setShowOk(false);
    setDsType("");
  };

  const onCloseClone = () => {
    setCloneVisible(false);
    setConfig({});
    form.resetFields();
  };

  useImperativeHandle(ref, () => ({
    onOpen,
    cloneDs,
  }));

  const getPortForType = (type: string) => {
    switch (type.toLowerCase()) {
      case "mysql":
        return 3306; // 默认 MySQL 端口
      case "postgresql":
        return 5432; // 默认 PostgreSQL 端口
      case "oracle":
        return 1521; // 默认 Oracle 端口
      case "sqlserver":
        return 1433; // 默认 SQL Server 端口
      case "mongodb":
        return 27017; // 默认 MongoDB 端口
      case "redis":
        return 6379; // 默认 Redis 端口
      case "hive":
        return 10000; // 默认 Hive 端口
      case "elasticsearch":
        return 9200; // 默认 Elasticsearch 端口
      default:
        return "";
    }
  };

  const selectSource = (dsSource: string, flag: boolean) => {
    setShowOk(flag);
    setDsType(dsSource);
    form.setFieldsValue({
      port: getPortForType(dsSource),
    });
  };

  const isFilter = () => {
    return ["PHOENIX"].includes(dsType);
  };

  const render = (
    <div style={{ padding: "0 16px" }}>
      <Form form={form} labelCol={{ span: 3 }} wrapperCol={{ span: 19 }}>
        <div className="lf-dwh-baseInfo">基础信息：</div>
        <Form.Item
          label={
            <div style={{ height: 32, lineHeight: "33px" }}>数据源名称</div>
          }
          name="dsName"
          rules={[{ required: true, message: "数据源名称不能为空" }]}
        >
          <Input placeholder="数据源名称" maxLength={100} size="small" />
        </Form.Item>

        <Form.Item
          label={
            <div style={{ height: 32, lineHeight: "33px" }}>数据源描述</div>
          }
          name="description"
        >
          <TextArea placeholder="数据源描述" maxLength={200} />
        </Form.Item>
        <Form.Item
          label={<div style={{ height: 32, lineHeight: "33px" }}>主机地址</div>}
          name="ipAddress"
          rules={[
            { required: true, message: "主机地址不能为空" },
            {
              pattern: ipRegex,
              message: "请输入有效的 IP 地址!",
            },
          ]}
        >
          <Input placeholder="主机地址 eg: 127.0.0.1" size="small" />
        </Form.Item>
        {!isFilter() ? (
          <Form.Item
            label={
              <div style={{ height: 32, lineHeight: "33px" }}>数据库名称</div>
            }
            name="dbName"
            rules={[{ required: true, message: "数据库名称不能为空" }]}
          >
            <Input placeholder="数据库名称" maxLength={100} size="small" />
          </Form.Item>
        ) : (
          ""
        )}

        <Form.Item
          label={<div style={{ height: 32, lineHeight: "33px" }}>端口</div>}
          name="port"
          rules={[{ required: true, message: "端口不能为空" }]}
        >
          <InputNumber placeholder="端口" maxLength={100} size="small" />
        </Form.Item>
        <Form.Item
          label={<div style={{ height: 32, lineHeight: "33px" }}>用户名</div>}
          name="username"
          rules={[
            {
              required: !isFilter(),
              message: "用户名不能为空",
            },
          ]}
        >
          <Input placeholder="用户名" maxLength={100} size="small" />
        </Form.Item>
        <Form.Item
          label={<div style={{ height: 32, lineHeight: "33px" }}>密码</div>}
          name="password"
          rules={[
            {
              required: !isFilter(),
              message: "密码不能为空",
            },
          ]}
        >
          <Input.Password placeholder="密码" maxLength={100} size="small" />
        </Form.Item>

        <div
          style={{
            paddingLeft: "130px",
          }}
        >
          <Form.List name="customParams">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <Space
                    key={key}
                    style={{ display: "flex", marginBottom: 8 }}
                    align="baseline"
                  >
                    <Form.Item
                      {...restField}
                      name={[name, "key"]}
                      rules={[{ required: true, message: "键不能为空" }]}
                    >
                      <Input
                        placeholder="输入键"
                        size="small"
                        style={{ width: "400px" }}
                      />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, "value"]}
                      rules={[{ required: true, message: "值不能为空" }]}
                    >
                      <Input
                        placeholder="输入值"
                        size="small"
                        style={{ width: "400px" }}
                      />
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    size="small"
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                  >
                    添加数据库连接参数
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </div>
      </Form>
    </div>
  );

  return (
    <>
      <Modal
        className="config-manage-value-modal"
        title={`${type === ConfigOperate.Add ? "新增" : "编辑"}${
          dsType === "" ? "" : " " + dsType + " "
        }数据源`}
        width={1100}
        visible={visible}
        maskClosable={false}
        onCancel={onClose}
        centered={true}
        footer={
          <div style={{ textAlign: "right" }}>
            {showOk === true ? (
              <>
                <Button
                  onClick={() => {
                    setShowOk(false);
                    setDsType("");
                  }}
                  style={{ marginRight: 8 }}
                >
                  上一步
                </Button>

                <Button
                  // onClick={onClose}
                  onClick={onSubmit}
                  style={{ marginRight: 8 }}
                  type="primary"
                >
                  完成
                </Button>
              </>
            ) : type === ConfigOperate.Add ? (
              <Button>取消</Button>
            ) : (
              <Button
                // onClick={onClose}
                onClick={onSubmit}
                style={{ marginRight: 8 }}
                type="primary"
              >
                完成
              </Button>
            )}
          </div>
        }
        destroyOnClose
      >
        {showOk ? (
          render
        ) : type === ConfigOperate.Add ? (
          <div style={{ height: "60vh", overflow: "auto", padding: "0 16px" }}>
            <SearchFilter data={sourceList} selectSource={selectSource} />
          </div>
        ) : (
          render
        )}
      </Modal>

      <Modal
        className="config-manage-value-modal"
        title={`克隆数据源`}
        width={500}
        visible={cloneVisible}
        maskClosable={false}
        onCancel={onCloseClone}
        centered={true}
        footer={
          <div style={{ textAlign: "right" }}>
            <Button
              // onClick={onClose}
              onClick={() => {
                form.validateFields().then((formData) => {
                  HttpUtils.post(api.cloneSource, {
                    id: config?.id,
                    dsName: formData?.newDsName,
                  }).then(
                    (res) => {
                      if (res?.code === 200) {
                        // 执行回调，刷新列表数据
                        callback.current();
                        onCloseClone();
                        message.success(`成功克隆数据源`);
                      } else {
                        message.error(res?.message);
                      }
                    },
                    () => setConfirmLoading(false)
                  );
                });
              }}
              style={{ marginRight: 8 }}
              type="primary"
            >
              完成
            </Button>
          </div>
        }
        destroyOnClose
      >
        <div style={{ padding: "0 16px" }}>
          <Form form={form} labelCol={{ span: 8 }} wrapperCol={{ span: 12 }}>
            <Form.Item
              label={
                <div style={{ height: 32, lineHeight: "33px" }}>原数据源</div>
              }
              name="dsName"
            >
              <Input maxLength={100} size="small" disabled />
            </Form.Item>

            <Form.Item
              label={
                <div style={{ height: 32, lineHeight: "33px" }}>
                  新数据源名称
                </div>
              }
              rules={[{ required: true, message: "新数据源不能为空" }]}
              name="newDsName"
            >
              <Input size="small" maxLength={100} />
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </>
  );
});

export default AddAndEditDataSourceModal;
